package com.zhanjixun.weixin.runnable;

import com.alibaba.fastjson.JSON;
import com.zhanjixun.weixin.Weixin;
import com.zhanjixun.weixin.WxMsgHandler;
import com.zhanjixun.weixin.conts.AppMsgType;
import com.zhanjixun.weixin.conts.MsgType;
import com.zhanjixun.weixin.domain.*;
import com.zhanjixun.weixin.utils.ContentTools;
import com.zhanjixun.weixin.utils.U;
import com.zhanjixun.weixin.utils.UserTools;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 同步检查线程
 *
 * @author :zhanjixun
 * @date : 2018/11/18 11:02
 */
@Log4j
public class SyncCheckAsyncTask implements Runnable {

    private Weixin weixin;

    public SyncCheckAsyncTask(Weixin weixin) {
        this.weixin = weixin;
    }

    @Override
    public void run() {
        log.debug("开启同步检测线程");
        while (true) {
            //检查服务器同步
            SyncCheck syncCheck = null;
            try {
                U.sleep(7);//冥冥之中自有7意
                syncCheck = weixin.getWxService().syncCheck();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (syncCheck == null) {
                continue;
            }
            if (syncCheck.getRetCode() == 0) {
                if (syncCheck.getSelector() != 0) {
                    try {
                        webWxSync();
                    } catch (Exception ignored) {

                    }
                }
            } else if (syncCheck.getRetCode() == 1101) {
                log.warn("微信会话已过期 " + JSON.toJSONString(syncCheck));
                break;
            } else if (syncCheck.getRetCode() == 1102) {
                log.warn("微信退出登录 " + JSON.toJSONString(syncCheck));
                break;
            } else {
                log.warn("未知状态：" + JSON.toJSONString(syncCheck));
            }
        }
        log.warn("同步检测线程已终止");
    }

    private void webWxSync() {
        WxSyncDTO wxSyncDTO = weixin.getWxService().webWxSync();
        String userName = weixin.getWxInitDataDTO().getUser().getUserName();
        //有新消息
        if (wxSyncDTO.getAddMsgCount() > 0) {
            List<WxMsg> addMsgList = wxSyncDTO.getAddMsgList();
            //添加自己在其他设备发的消息在发送历史中
            List<WxMsg> selfMsg = addMsgList.stream().filter(m -> m.getFromUserName().equals(userName)).collect(Collectors.toList());
            weixin.getMsgSendHistory().addAll(selfMsg);
            //过滤掉自己发出的消息(在其他设备发的消息也会传到网页版这里来,需要过滤掉)
            List<WxMsg> msgList = addMsgList.stream().filter(m -> !m.getFromUserName().equals(userName)).collect(Collectors.toList());
            weixin.getMsgHistory().addAll(msgList);
            msgList.forEach(this::handleMsg);
        }
        //通讯录修改
        if (wxSyncDTO.getModContactCount() > 0) {
            List<ModContact> modContactList = wxSyncDTO.getModContactList();
        }
        //通讯录删除
        if (wxSyncDTO.getDelContactCount() > 0) {
            List<String> delContactList = wxSyncDTO.getDelContactList();
        }
        //群聊修改
        if (wxSyncDTO.getModChatRoomMemberCount() > 0) {
            List<String> modChatRoomMemberList = wxSyncDTO.getModChatRoomMemberList();
        }
    }

    private void handleMsg(WxMsg msg) {
        String fromNickName = UserTools.userName2nickName(msg.getFromUserName());
        WxMsgHandler msgHandler = msg.isGroupMsg() ? weixin.getGroupMsgHandler() : weixin.getMsgHandler();
        if (msgHandler == null) {
            return;
        }

        MsgType msgType = MsgType.getMsgTypeByCode(msg.getMsgType());
        if (msgType == MsgType.TEXT) {
            //文本消息 subMsgType是0
            if (msg.getSubMsgType() == 0) {
                if (msg.isGroupMsg()) {
                    ContactMember group = UserTools.getContactMemberByUserName(msg.getFromUserName());
                    String content = StringUtils.substringAfter(msg.getContent(), ":<br/>");
                    log.info(String.format("[群组消息][%s]%s", group.getNickName(), content));
                } else {
                    log.info(String.format("[%s]发来消息：%s", fromNickName, msg.getContent()));
                }
                msgHandler.handleTextMsg(msg);
            }
            //位置消息 subMsgType是48
            if (msg.getSubMsgType() == 48) {
                LocationMsg locationMsg = ContentTools.toLocationMsg(msg.getOriContent());
                log.info(String.format("[地理位置]%s:%s", fromNickName, locationMsg.getLabel()));
                msgHandler.handleLocationMsg(msg);
            }
        }
        if (msgType == MsgType.IMAGE) {
            msgHandler.handleImageMsg(msg);
        }
        if (msgType == MsgType.REVOKE) {
            msgHandler.handleRevokeMsg(msg);
        }
        if (msgType == MsgType.ANIMATED_STICKER) {
            log.info(String.format("[动画表情]%s发来一个动画表情", fromNickName));
            msgHandler.handleEmoticonMsg(msg);
        }
        if (msgType == MsgType.VOICE) {
            log.info(String.format("[语音]%s发来一个语音,长度：%d秒", fromNickName, msg.getVoiceLength() / 1000));
            msgHandler.handleVoiceMsg(msg);
        }
        if (msgType == MsgType.VIDEO) {
            log.info(String.format("[视频]%s发来一个视频", fromNickName));
            msgHandler.handleVideoMsg(msg);
        }
        if (msgType == MsgType.APP) {
            AppMsgType appMsgType = AppMsgType.getMsgTypeByCode(msg.getAppMsgType());
            if (msg.getAppMsgType() == 0) {
                //目前见过在邀请进群时候出现、转发收藏信息也有出现
            }
            if (appMsgType == AppMsgType.LINK) {
                log.info(String.format("[链接]%s:%s", fromNickName, msg.getFileName()));
                msgHandler.handleLinkMsg(msg);
            }
            if (appMsgType == AppMsgType.FILE) {
                log.info(String.format("[文件]%s:%s", fromNickName, msg.getFileName()));
                msgHandler.handleFileMsg(msg);
            }
            if (appMsgType == AppMsgType.MINI_PROGRAM) {
                log.info(String.format("[小程序]%s:%s", fromNickName, msg.getFileName()));
                msgHandler.handleMiniProgramMsg(msg);
            }
        }
        if (msgType == MsgType.SHARE_CARD) {
            msgHandler.handleCardMsg(msg);
        }
        if (msgType == MsgType.SYSTEM) {
            log.info("[系统消息]" + msg.getContent());
            msgHandler.handleSysMsg(msg);
        }
    }
}
